#!/usr/bin/perl
#file tcp_echo_cli1.pl
# usage: tcp_echo_cli1.pl [host] [port]
# Echo client, Tcp Version

use strict;
use Socket;
use IO::Socket;
use IO::Handle;
my $socket = IO::Socket::INET->new();
my ($bytes_out, $bytes_in) = (0,0);
my $host = shift || 'localhost';
my $port = shift || getservbyname('echo', 'tcp');       # 默认echo 服务。

my $protocol = getprotobyname('tcp');
$host = inet_aton($host) or die "$host: unknown host";

socket(SOCK, AF_INET, SOCK_STREAM, $protocol) or die "socket() failed: $!";
my $dest_addr = sockaddr_in($port, $host);
connect(SOCK, $dest_addr) or die "connect() failed: $!";

# select SOCK; $| = 1; select STDOUT; $| = 1;

STDOUT->autoflush(1);
SOCK->autoflush(1);
# while($socket->recv(my $msg_out, 1000) >= 0){
while(my $msg_out = <>){
    #print SOCK $msg_out;
    syswrite (SOCK, $msg_out);
    my $msg_in = <SOCK>;
    syswrite (STDOUT, $msg_in);

    $bytes_out += length($msg_out);
    $bytes_in += length($msg_in);
}

close(SOCK);
print STDERR "bytes_sent = $bytes_out, bytes_received = $bytes_in\n";